<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-10-03 11:14:46
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;

use App\Models\FinanceReceiving;
use App\Models\MarketRetail;
use App\Models\MarketRetailDetails;

/**
 * @property MarketRetail $model
 * @property FinanceReceiving $finance
 */
class MarketRetailRepository extends Repositories
    {
    protected $relation_models = ['department', 'fauditor', 'status', 'tax', 'fstatus', 'customer', 'singler', 'creator', 'updator', 'attachments', 'collection', 'car' => ['company'], 'carry' => ['company']];
    public function boot(MarketRetail $model, FinanceReceiving $finance)
        {
        $this->model   = $model;
        $this->finance = $finance;
        }


    public function saveCollection($collection, $gdata)
        {
        //保存收款单！
        $NotNeedDeleteFinance = [];
        array_filter($collection, function ($v) use ($gdata, &$NotNeedDeleteFinance)
            {
            if (is_numeric($v['id'] ?? "") && $v['id'] > 0) {
                $debtor_data = $this->finance->whereId($v['id'])->first();
                //收款单已审核
                if ($debtor_data['status_id'] != 0) {
                    if ($v['amount'] != $debtor_data['amount'] || $v['subject_id'] != $debtor_data['subject_id']) {
                        fail("关联的收款单{$debtor_data->code}{$debtor_data->status->name}！禁止删除修改！");
                        }
                    }
                if ($v['tax_id'] == 1 && $gdata['billtrade'] != $debtor_data->billtrade) {
                    fail("关联的收款单{$debtor_data->code}{$debtor_data->status->name}！禁止删除修改收款选项！");
                    }
                }
            if (!isset($v['amount']) || $v['amount'] <= 0) {
                fail("收款金额必须填写!");
                }
            if (!isset($v['subject_id']) || $v['subject_id'] <= 0) {
                fail("收款银行卡必须填写！!");
                }
            $v['state']             = 1;
            $v['order_code']        = $gdata->code;
            $v['company_id']        = $gdata['customer_id'];
            $v['employee_id']       = $gdata['creator_id'];
            $v['billtrade']         = $v['tax_id'] == 1 ? $gdata['billtrade'] : "";
            $NotNeedDeleteFinance[] = $this->finance->setACSign("DEBTOR")->firstOrCreate(['id' => $v['id'] ?? 0], $v)?->id ?? 0;

            });
        $this->finance->whereOrder_code($gdata->code)->whereNotIn("id", $NotNeedDeleteFinance)->get()->filter(function ($v)
            {
            if ($v->status_id == 1) {
                fail("收款单[{$v['code']}]已审核！禁止删除！");
                }
            $v->delete();
            });
        }

    }